import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { getUserInfoApi } from '@/api'
import { useCartStore } from '@/stores'

export const useUserStore = defineStore(
  'user',
  () => {
    // token
    const token = ref('')
    // 用户信息
    const userInfo = ref({
      avatar: '',
      email: '',
      id: '',
      integral: '',
      is_new_member: 1, // 1 新用户 0 老用户
      name: '',
    })

    const setToken = (t) => {
      const { uploadCart } = useCartStore()
      token.value = t
      uploadCart()
      getUserInfo()
    }

    const getUserInfo = () => {
      getUserInfoApi().then((res) => {
        userInfo.value = res
      })
    }

    const logout = () => {
      token.value = ''
      userInfo.value = {}
    }

    return {
      token,
      userInfo,
      setToken,
      getUserInfo,
      logout,
    }
  },
  {
    persist: true,
  },
)
